using System;
using System.Xml;

namespace stunnware.CRM.Fetch
{
    /// <summary>
    /// The FetchEntity represents the root element in a FetchXML expression. It occurs exactly once.
    /// </summary>
    public class FetchEntity : FetchEntityBase
    {

        public FetchEntity() { }
        /// <summary>
        /// Creates a new instance bound to the specified entity.
        /// </summary>
        /// <param name="entityName">The entity name.</param>
        public FetchEntity(string entityName)
            : base(entityName)
        {
        }

        /// <summary>
        /// Adds the definition of this class to an XML document.
        /// </summary>
        /// <param name="doc"></param>
        internal void AddToFetchDocument(FetchXmlDocument doc)
        {

            XmlElement entity = doc.AddRootElement("entity");
            FetchXmlDocument.AddAttribute(entity, "name", EntityName);

            base.AddElements(entity);
        }

        /// <summary>
        /// Parses the passed xml node and creates a new instance from it.
        /// </summary>
        /// <param name="node"></param>
        /// <returns></returns>
        public static FetchEntity FromXml(XmlNode node)
        {

            XmlAttribute attr = node.Attributes["name"];

            if (attr == null)
            {
                throw new XmlException("The name attribute in missing in the entity node.");
            }

            FetchEntity entity = new FetchEntity(attr.Value);
            entity.PopulateFromXml(node);

            return entity;
        }
    }
}
